package android.cs2340UDT;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Database implements Serializable{
	
	private String KEY_USERNAME;
	
	private static final long sVersionID = 1L;
	private static Logger myLogger = Logger.getLogger("User");
	
	private List<User> users;
	private transient int codeCheck;
	
	public Database(String name){
		KEY_USERNAME = name;
		users = new ArrayList<User>();
		codeCheck = 111;
	}
	
	public void save(String filename, Object object){
		try{
			FileOutputStream outputStream = new FileOutputStream(filename);
			ObjectOutputStream outputObject = new ObjectOutputStream(outputStream);
			outputObject.writeObject(object);
			outputObject.flush();
			outputObject.close();
		} catch(FileNotFoundException e){
			myLogger.log(Level.SEVERE, "Save file not found: " + filename, e);
		} catch(IOException e){
			myLogger.log(Level.SEVERE, "General IO Error on Saving: " + filename, e);
		}
	}
	
	public List<User> getUsers(){
		return users;
	}
	
	public String getUsername(){
		return KEY_USERNAME;
	}
	
	public int getCode(){
		return codeCheck;
	}
	
	public void addUser(User u){
		users.add(u);
	}
	
	public static Database getFromFile(String filename){
		Database d = null;
		try{
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename));
			d = (Database) in.readObject();
		} catch(FileNotFoundException e){
            myLogger.log(Level.SEVERE, "Load file not found: " + filename, e);
        } catch (IOException e) {
            myLogger.log(Level.SEVERE, "General IO Error on loading: " + filename, e);
        } catch (ClassNotFoundException e) {
            myLogger.log(Level.SEVERE, "Company class not found on loading: " + filename, e);
        }
        return d;
     }
	
	
	public boolean hasUserNamed(String name){
		for(User u: users){
			if(u.getUsername().equals(name))
				return true;
		}
		return false;
	}
}
	
	
